﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

namespace QLNHK.BLL
{
	public partial class DataBackup : Ent_Base, ICloneable
	{
        #region Variables
        
		private int _iD;
		private string _name = string.Empty;
		private string _path = string.Empty;
		private DateTime _dateCreated = new DateTime(1753, 1, 1);
		private decimal _size;
		private string _notes = string.Empty;
        
        #endregion
    
        //---------------------------------------------------------------------------------------------
        
		#region Properties.
		
		public int ID 
        { 
            get { return  _iD; } 
            set
            {
                _iD = value;
                OnPropertyChanged("ID");
            }
        }
		public string Name 
        { 
            get { return  _name; } 
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
		public string Path 
        { 
            get { return  _path; } 
            set
            {
                _path = value;
                OnPropertyChanged("Path");
            }
        }
		public DateTime DateCreated 
        { 
            get { return  _dateCreated; } 
            set
            {
                _dateCreated = value;
                OnPropertyChanged("DateCreated");
            }
        }
		public decimal Size 
        { 
            get { return  _size; } 
            set
            {
                _size = value;
                OnPropertyChanged("Size");
            }
        }
		public string Notes 
        { 
            get { return  _notes; } 
            set
            {
                _notes = value;
                OnPropertyChanged("Notes");
            }
        }
		
		#endregion
		
		//---------------------------------------------------------------------------------------------
		
		#region Methods
		protected static List<DataBackup> ConvertToCollection(IDataReader reader)
		{
			List<DataBackup> collection = new List<DataBackup>();
			while (reader.Read())
			{
				DataBackup entity = new DataBackup();
				if (!reader.IsDBNull(reader.GetOrdinal("ID"))) entity.ID = reader.GetInt32(reader.GetOrdinal("ID"));
				if (!reader.IsDBNull(reader.GetOrdinal("Name"))) entity.Name = reader.GetString(reader.GetOrdinal("Name"));
				if (!reader.IsDBNull(reader.GetOrdinal("Path"))) entity.Path = reader.GetString(reader.GetOrdinal("Path"));
				if (!reader.IsDBNull(reader.GetOrdinal("DateCreated"))) entity.DateCreated = reader.GetDateTime(reader.GetOrdinal("DateCreated"));
				if (!reader.IsDBNull(reader.GetOrdinal("Size"))) entity.Size = reader.GetDecimal(reader.GetOrdinal("Size"));
				if (!reader.IsDBNull(reader.GetOrdinal("Notes"))) entity.Notes = reader.GetString(reader.GetOrdinal("Notes"));
				collection.Add(entity);
			}
			reader.Close();
			return collection;
		}
		
		public static bool Find(List<DataBackup> collection, int iD)
        {
            foreach (DataBackup item in collection)
            {
                if (item.ID == iD)
                {
                    return true;
                }
            }

            return false;
        }
		
		public static void UpdateDataSet(DataSet ds)
        {
            string insert = "Insert INTO tb_Sys_DataBackup VALUES(@Name, @Path, @DateCreated, @Size, @Notes)";
            string update = "UPDATE tb_Sys_DataBackup SET Name = @Name, Path = @Path, DateCreated = @DateCreated, Size = @Size, Notes = @Notes WHERE ID = @ID";
            string delete = "DELETE FROM tb_Sys_DataBackup WHERE ID = @ID";

			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();

            System.Data.Common.DbCommand InsertCommand = db.GetSqlStringCommand(insert);
			db.AddInParameter(InsertCommand, "@ID", SqlDbType.Int, "ID", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Name", SqlDbType.NVarChar, "Name", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Path", SqlDbType.NVarChar, "Path", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@DateCreated", SqlDbType.DateTime, "DateCreated", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Size", SqlDbType.Decimal, "Size", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Notes", SqlDbType.NVarChar, "Notes", DataRowVersion.Current);

            System.Data.Common.DbCommand UpdateCommand = db.GetSqlStringCommand(update);
			db.AddInParameter(UpdateCommand, "@ID", SqlDbType.Int, "ID", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Name", SqlDbType.NVarChar, "Name", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Path", SqlDbType.NVarChar, "Path", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@DateCreated", SqlDbType.DateTime, "DateCreated", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Size", SqlDbType.Decimal, "Size", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Notes", SqlDbType.NVarChar, "Notes", DataRowVersion.Current);
			
            System.Data.Common.DbCommand DeleteCommand = db.GetSqlStringCommand(delete);
			db.AddInParameter(DeleteCommand, "@ID", SqlDbType.Int, "ID", DataRowVersion.Current);

            db.UpdateDataSet(ds, ds.Tables[0].TableName, InsertCommand, UpdateCommand, DeleteCommand, UpdateBehavior.Standard);
        }
				
		public static void UpdateDataSet(DataSet ds, string tableName)
        {
            string insert = "Insert INTO tb_Sys_DataBackup VALUES(@Name, @Path, @DateCreated, @Size, @Notes)";
            string update = "UPDATE tb_Sys_DataBackup SET Name = @Name, Path = @Path, DateCreated = @DateCreated, Size = @Size, Notes = @Notes WHERE ID = @ID";
            string delete = "DELETE FROM tb_Sys_DataBackup WHERE ID = @ID";

			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();

            System.Data.Common.DbCommand InsertCommand = db.GetSqlStringCommand(insert);
			db.AddInParameter(InsertCommand, "@ID", SqlDbType.Int, "ID", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Name", SqlDbType.NVarChar, "Name", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Path", SqlDbType.NVarChar, "Path", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@DateCreated", SqlDbType.DateTime, "DateCreated", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Size", SqlDbType.Decimal, "Size", DataRowVersion.Current);
			db.AddInParameter(InsertCommand, "@Notes", SqlDbType.NVarChar, "Notes", DataRowVersion.Current);

            System.Data.Common.DbCommand UpdateCommand = db.GetSqlStringCommand(update);
			db.AddInParameter(UpdateCommand, "@ID", SqlDbType.Int, "ID", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Name", SqlDbType.NVarChar, "Name", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Path", SqlDbType.NVarChar, "Path", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@DateCreated", SqlDbType.DateTime, "DateCreated", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Size", SqlDbType.Decimal, "Size", DataRowVersion.Current);
			db.AddInParameter(UpdateCommand, "@Notes", SqlDbType.NVarChar, "Notes", DataRowVersion.Current);
			
            System.Data.Common.DbCommand DeleteCommand = db.GetSqlStringCommand(delete);
			db.AddInParameter(DeleteCommand, "@ID", SqlDbType.Int, "ID", DataRowVersion.Current);

            db.UpdateDataSet(ds, tableName, InsertCommand, UpdateCommand, DeleteCommand, UpdateBehavior.Standard);
        }

		#endregion
		
		//---------------------------------------------------------------------------------------------
		
		#region Select methods.
		
		public static DataBackup Load(int iD)
		{
			const string spName = "[dbo].[p_DataBackup_Load.generated]";
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
			SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);
			
			db.AddInParameter(dbCommand, "@ID", SqlDbType.Int, iD);
            IDataReader reader = db.ExecuteReader(dbCommand);
			List<DataBackup> collection = ConvertToCollection(reader);	
			if (collection.Count > 0)
			{
				return collection[0];
			}
			return null;
		}		
		
		//---------------------------------------------------------------------------------------------
		public static List<DataBackup> SelectCollectionAll()
		{
			IDataReader reader = SelectReaderAll();
			return ConvertToCollection(reader);			
		}		
		
		//---------------------------------------------------------------------------------------------
		
		public static List<DataBackup> SelectCollectionDynamic(string whereCondition, string orderByExpression)
		{
			IDataReader reader = SelectReaderDynamic(whereCondition, orderByExpression);
			return ConvertToCollection(reader);		
		}
		
		//---------------------------------------------------------------------------------------------
		
		// Select by foreign key return collection		
		

		public static DataSet SelectAll()
        {
            const string spName = "[dbo].[p_DataBackup_SelectAll.generated]";
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			
            return db.ExecuteDataSet(dbCommand);
        }
		
		//---------------------------------------------------------------------------------------------
		
		public static DataSet SelectDynamic(string whereCondition, string orderByExpression)
		{
            const string spName = "[dbo].[p_DataBackup_SelectDynamic.generated]";
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			db.AddInParameter(dbCommand, "@WhereCondition", SqlDbType.NVarChar, whereCondition);
            db.AddInParameter(dbCommand, "@OrderByExpression", SqlDbType.NVarChar, orderByExpression);
            
            return db.ExecuteDataSet(dbCommand);        				
		}
		
		//---------------------------------------------------------------------------------------------
				
		public static IDataReader SelectReaderAll()
        {
            const string spName = "[dbo].[p_DataBackup_SelectAll.generated]";
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);
			
            return db.ExecuteReader(dbCommand);
        }
		
		//---------------------------------------------------------------------------------------------
		
		public static IDataReader SelectReaderDynamic(string whereCondition, string orderByExpression)
		{
            const string spName = "[dbo].[p_DataBackup_SelectDynamic.generated]";
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			db.AddInParameter(dbCommand, "@WhereCondition", SqlDbType.NVarChar, whereCondition);
            db.AddInParameter(dbCommand, "@OrderByExpression", SqlDbType.NVarChar, orderByExpression);
            
            return db.ExecuteReader(dbCommand);        				
		}
		
		//---------------------------------------------------------------------------------------------
		
		// Select by foreign key return collection		
		
		#endregion
		
		//---------------------------------------------------------------------------------------------
		
		#region Insert methods.
		
		public static int InsertDataBackup(string name, string path, DateTime dateCreated, decimal size, string notes)
		{
			DataBackup entity = new DataBackup();	
			entity.Name = name;
			entity.Path = path;
			entity.DateCreated = dateCreated;
			entity.Size = size;
			entity.Notes = notes;
			return entity.Insert();
		}
		
		public int Insert()
		{
			return this.Insert(null);
		}		
		
		//---------------------------------------------------------------------------------------------
		
		public int Insert(SqlTransaction transaction)
		{			
			const string spName = "[dbo].[p_DataBackup_Insert.generated]";		
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			db.AddOutParameter(dbCommand, "@ID", SqlDbType.Int, 4);
			db.AddInParameter(dbCommand, "@Name", SqlDbType.NVarChar, Name);
			db.AddInParameter(dbCommand, "@Path", SqlDbType.NVarChar, Path);
			db.AddInParameter(dbCommand, "@DateCreated", SqlDbType.DateTime, DateCreated.Year <= 1753 ? DBNull.Value : (object) DateCreated);
			db.AddInParameter(dbCommand, "@Size", SqlDbType.Decimal, Size);
			db.AddInParameter(dbCommand, "@Notes", SqlDbType.NVarChar, Notes);
			
			if (transaction != null)
			{
				db.ExecuteNonQuery(dbCommand, transaction);
				ID = (int) db.GetParameterValue(dbCommand, "@ID");
				return ID;
			}
            else
			{
				db.ExecuteNonQuery(dbCommand);
				ID = (int) db.GetParameterValue(dbCommand, "@ID");
				return ID;
			}			
		}
				
		//---------------------------------------------------------------------------------------------
		public static bool InsertCollection(List<DataBackup> collection)
        {
            bool ret;
			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                using(SqlTransaction transaction = connection.BeginTransaction())
				{
					try
					{
						bool ret01 = true;
						foreach (DataBackup item in collection)
						{
							if (item.Insert(transaction) <= 0)
							{							
								ret01 = false;
								break;
							}
						}
						if (ret01)
						{
							transaction.Commit();
							ret = true;
						}
						else
						{
							transaction.Rollback();
							ret = false;                    	
						}
					}
					catch (Exception ex)
					{
						transaction.Rollback();
						throw new Exception("Error at InsertCollection method: " + ex.Message);
					}
					finally 
					{
						connection.Close();
					}
				}
            }
            return ret;		
		}
		
		#endregion
		
		//---------------------------------------------------------------------------------------------
		
		#region Insert / Update methods.
		
		public static int InsertUpdateDataBackup(int iD, string name, string path, DateTime dateCreated, decimal size, string notes)
		{
			DataBackup entity = new DataBackup();			
			entity.ID = iD;
			entity.Name = name;
			entity.Path = path;
			entity.DateCreated = dateCreated;
			entity.Size = size;
			entity.Notes = notes;
			return entity.InsertUpdate();
		}
		
		//---------------------------------------------------------------------------------------------
		
		public int InsertUpdate()
		{
			return this.InsertUpdate(null);
		}
		
		//---------------------------------------------------------------------------------------------

		public int InsertUpdate(SqlTransaction transaction)
		{			
			const string spName = "[dbo].p_DataBackup_InsertUpdate.generated]";		
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
			SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			db.AddInParameter(dbCommand, "@ID", SqlDbType.Int, ID);
			db.AddInParameter(dbCommand, "@Name", SqlDbType.NVarChar, Name);
			db.AddInParameter(dbCommand, "@Path", SqlDbType.NVarChar, Path);
			db.AddInParameter(dbCommand, "@DateCreated", SqlDbType.DateTime, DateCreated.Year <= 1753 ? DBNull.Value : (object) DateCreated);
			db.AddInParameter(dbCommand, "@Size", SqlDbType.Decimal, Size);
			db.AddInParameter(dbCommand, "@Notes", SqlDbType.NVarChar, Notes);
			
			if (transaction != null)
                return db.ExecuteNonQuery(dbCommand, transaction);
            else
                return db.ExecuteNonQuery(dbCommand);			
		}
		
		//---------------------------------------------------------------------------------------------
		public static bool InsertUpdateCollection(List<DataBackup> collection)
        {
            bool ret;
			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                using (SqlTransaction transaction = connection.BeginTransaction())
				{
					try
					{
						bool ret01 = true;
						foreach (DataBackup item in collection)
						{
							if (item.InsertUpdate(transaction) <= 0)
							{
								ret01 = false;
								break;
							}
						}
						if (ret01)
						{
							transaction.Commit();
							ret = true;
						}
						else
						{
							transaction.Rollback();
							ret = false;                    	
						}
					}
					catch (Exception ex)
					{
						transaction.Rollback();
						throw new Exception("Error at InsertUpdateCollection method: " + ex.Message);
						
					}
					finally 
					{
						connection.Close();
					}
				}
            }
            return ret;		
		}	
		#endregion
		
		//---------------------------------------------------------------------------------------------
		
		#region Update methods.
		
		public static int UpdateDataBackup(int iD, string name, string path, DateTime dateCreated, decimal size, string notes)
		{
			DataBackup entity = new DataBackup();			
			entity.ID = iD;
			entity.Name = name;
			entity.Path = path;
			entity.DateCreated = dateCreated;
			entity.Size = size;
			entity.Notes = notes;
			return entity.Update();
		}
		
		//---------------------------------------------------------------------------------------------
		
		public int Update()
		{
			return this.Update(null);
		}
		
		//---------------------------------------------------------------------------------------------

		public int Update(SqlTransaction transaction)
		{
			const string spName = "[dbo].[p_DataBackup_Update.generated]";		
			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
			SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			db.AddInParameter(dbCommand, "@ID", SqlDbType.Int, ID);
			db.AddInParameter(dbCommand, "@Name", SqlDbType.NVarChar, Name);
			db.AddInParameter(dbCommand, "@Path", SqlDbType.NVarChar, Path);
			db.AddInParameter(dbCommand, "@DateCreated", SqlDbType.DateTime, DateCreated.Year <= 1753 ? DBNull.Value : (object) DateCreated);
			db.AddInParameter(dbCommand, "@Size", SqlDbType.Decimal, Size);
			db.AddInParameter(dbCommand, "@Notes", SqlDbType.NVarChar, Notes);
			
			if (transaction != null)
                return db.ExecuteNonQuery(dbCommand, transaction);
            else
                return db.ExecuteNonQuery(dbCommand);
		}
				
		//---------------------------------------------------------------------------------------------
		public static bool UpdateCollection(List<DataBackup> collection)
        {
            bool ret;
			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                using (SqlTransaction transaction = connection.BeginTransaction())
				{
					try
					{
						bool ret01 = true;
						foreach (DataBackup item in collection)
						{
							if (item.Update(transaction) <= 0)
							{
								ret01 = false;
								break;
							}
						}
						if (ret01)
						{
							transaction.Commit();
							ret = true;
						}
						else
						{
							transaction.Rollback();
							ret = false;                    	
						}
					}
					catch (Exception ex)
					{
						transaction.Rollback();
						throw new Exception("Error at UpdateCollection method: " + ex.Message);
					}
					finally 
					{
						connection.Close();
					}
				}
            }
            return ret;		
		}
		
		#endregion
		
		//---------------------------------------------------------------------------------------------
		
		#region Delete methods.
		
		public static int DeleteDataBackup(int iD)
		{
			DataBackup entity = new DataBackup();
			entity.ID = iD;
			
			return entity.Delete();
		}
		
		public int Delete()
		{
			return this.Delete(null);
		}
		
		//---------------------------------------------------------------------------------------------

		public int Delete(SqlTransaction transaction)
		{
			const string spName = "[dbo].[p_DataBackup_Delete.generated]";		
			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
			SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);
			
			db.AddInParameter(dbCommand, "@ID", SqlDbType.Int, ID);
			
			if (transaction != null)
                return db.ExecuteNonQuery(dbCommand, transaction);
            else
                return db.ExecuteNonQuery(dbCommand);
		}
		
		//---------------------------------------------------------------------------------------------
		
		
		public static int DeleteDynamic(string whereCondition)
		{
			const string spName = "[dbo].[p_DataBackup_DeleteDynamic.generated]";
            SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand) db.GetStoredProcCommand(spName);

			db.AddInParameter(dbCommand, "@WhereCondition", SqlDbType.NVarChar, whereCondition);
            
            return db.ExecuteNonQuery(dbCommand);   
		}
		//---------------------------------------------------------------------------------------------
		
		public static bool DeleteCollection(List<DataBackup> collection)
        {
            bool ret;
			SqlDatabase db = (SqlDatabase) DatabaseFactory.CreateDatabase();
            using (SqlConnection connection = (SqlConnection)db.CreateConnection())
            {
                connection.Open();
                using (SqlTransaction transaction = connection.BeginTransaction())
				{
					try
					{
						bool ret01 = true;
						foreach (DataBackup item in collection)
						{
							if (item.Delete(transaction) <= 0)
							{
								ret01 = false;
								break;
							}
						}
						if (ret01)
						{
							transaction.Commit();
							ret = true;
						}
						else
						{
							transaction.Rollback();
							ret = false;                    	
						}
					}
					catch (Exception ex)
					{
						transaction.Rollback();
						throw new Exception("Error at DeleteCollection method: " + ex.Message);
					}
					finally 
					{
						connection.Close();
					}
				}
            }
            return ret;		
		}
		#endregion
		
        //---------------------------------------------------------------------------------------------
		
        #region ICloneable Members

        public object Clone()
        {
            return base.MemberwiseClone();
        }

        public DataBackup CloneObject()
        {
            return this.Clone() as DataBackup;
        }
        
        #endregion
	}	
}